package com.wesley.philosopher;

import java.util.concurrent.Executors;

/**
 * DiningPhilosophersDeadlock
 *
 * @author WangPanYong
 * @since 2023/05/10 16:43
 */
public class DiningPhilosophersDeadlock {

    Phi[] phis = new Phi[5];
    volatile int[] forks = new int[5];

    public DiningPhilosophersDeadlock(){
        for(int i = 0; i < 5; i++) {
            phis[i] = new Phi(i+1);
            forks[i] = 0;
        }
    }

    class Phi extends Philosopher {

        public Phi(int id) {
            super(id);
        }

        @Override
        protected synchronized boolean takeLeft(int[] forks) {
            return super.takeLeft(forks);
        }

        @Override
        protected synchronized boolean takeRight(int[] forks) {
            return super.takeRight(forks);
        }

        @Override
        public void run() {
            while (true) {
                try {
                    this.thinking();
                    while (!this.takeLeft(forks)) {
                        // 自旋等待
                        Thread.onSpinWait();
                    }
                    System.out.println(Thread.currentThread().getName() + ": takeLeft");
                    int c = 0;
                    // 死锁
                    while (!this.takeRight(forks)) {
                        c++;
                        if(c > 100) {
                            // livelock
                            this.putLeft(forks);
                            continue;
                        }
                        // 自旋等待
                        Thread.onSpinWait();
                    }
                    System.out.println(Thread.currentThread().getName() + ":takeRight");
                    this.eating();
                    this.putLeft(forks);
                    this.putRight(forks);
                    this.finished();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void run() {
        var pool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            pool.submit(phis[i]);
        }
    }

    public static void main(String[] argv) {
        var solver = new DiningPhilosophersDeadlock();
        solver.run();
    }
}
